# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

_GATEWAY = 'http://apid.abfmoney.com/gateway/v3/pay'
_QUERY_GATEWAY = 'http://apid.abfmoney.com/gateway/v3/query'

APP_CONF = {
    '190128': {  # 安保付 支付宝扫码 100—20000 2.5% dwc
        'API_KEY': '6e852354b8da41a69f296f151a86d6c8',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


# wxpay 为微信, alipay 为支付宝
def _get_pay_type(service):
    if service == 'wxpay':
        return 'wxpay'
    elif service == 'alipay':
        return 'alipay'
    else:
        return 'alipay'


def generate_sign(d, key):
    '''  生成下单签名 '''
    s = d['total_fee'] + d['pay_type'] + d['order_code'] + d['business_code'] + key
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().lower()
    return sign


# def generate_verify_sign(d, key):
#     '''  生成回调签名 '''
#     s = d['total_fee'] + d['pay_type'] + d['order_code'] + d['business_code'] + key
#     m = hashlib.md5()
#     m.update(s.encode('utf8'))
#     sign = m.hexdigest().lower()
#     return sign


def verify_notify_sign(params, key):
    md5 = params['md5']
    # params.pop(md5)
    calculated_sign = generate_sign(params, key)
    if md5 != calculated_sign:
        _LOGGER.info("anbaofupay sign: %s, calculated sign: %s", md5, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def create_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    service = info.get('service')
    parameter_dict = OrderedDict((
        ('business_code', app_id),
        ('order_code', str(pay.id)),
        ('total_fee', str(int(pay_amount * 100))),
        ('pay_type', _get_pay_type(service)),
        ('user_id', str(pay.user_id)),
        ('notify_url', '{}/pay/api/{}/anbaofupay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('return_url', '{}/pay/api/{}/anbaofupay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id)),
    ))

    parameter_dict['md5'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("anbaofupay create data: %s, order_id is: %s", json.dumps(parameter_dict),
                 parameter_dict['order_code'])
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_GATEWAY, data=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info("anbaofupay create rsp data: %s %s", response.status_code, response.text)
    extend = json.loads(pay.extend or '{}')
    extend.update({'pay_type': parameter_dict['pay_type']})
    order_db.fill_extend(pay.id, extend)
    return {'charge_info': json.loads(response.text)['data']['code_url']}


# ok
def check_notify_sign(request, app_id):
    data = dict(request.POST.iteritems())
    api_key = _get_api_key(app_id)
    _LOGGER.info("anbaofupay notify data1: %s", data)
    _LOGGER.info("anbaofupay notify body: %s", request.body)
    # data = json.loads(request.body)
    verify_notify_sign(data, api_key)
    pay_id = data['order_code']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('anbaofupay event does not contain pay ID')

    pay = order_db.get_pay(pay_id)
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['status'])
    trade_no = ''
    total_fee = float(data['total_fee']) / 100.0
    pay_type = json.loads(pay.extend or '{}').get('pay_type', 0)

    extend = {
        'pay_type': pay_type,
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == 'SUCCESS':
        _LOGGER.info('anbaofupay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    # prepare param
    pay_id = pay_order.id
    api_key = _get_api_key(app_id)
    pay_type = json.loads(pay_order.extend or '{}').get('pay_type', 0)
    parameter_dict = OrderedDict((
        ('total_fee', str(int(pay_order.total_fee * 100))),
        ('business_code', app_id),
        ('order_code', str(pay_id)),
        ('pay_type', pay_type),
        ('user_id', str(pay_order.user_id)),
    ))
    parameter_dict['md5'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("anbaofupay query data: %s, order_id is: %s", json.dumps(parameter_dict), parameter_dict['order_code'])
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_QUERY_GATEWAY, data=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info("anbaofupay query  rsp data: %s", response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        trade_status = str(data['status'])
        trade_no = ''
        total_fee = float(data['total_fee']) / 100.0

        extend = {
            'pay_type': pay_type,
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }

        # SUCCESS:支付成功， NOTPAY:未支付
        if trade_status == 'SUCCESS':
            _LOGGER.info('anbaofupay query order success, user_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('anbaofupay data error, status_code: %s', response.status_code)
